package com.gec.anan.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gec.anan.customer.mapper.CustomerInfoMapper;
import com.gec.anan.customer.mapper.CustomerLoginLogMapper;
import com.gec.anan.customer.service.CustomerInfoService;
import com.gec.anan.model.entity.customer.CustomerInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.anan.model.entity.customer.CustomerLoginLog;
import com.gec.anan.model.form.customer.UpdateWxPhoneForm;
import com.gec.anan.model.vo.customer.CustomerLoginVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Autowired
    private WxMaService service;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 条件：
     * 1、前端开发者appid与服务器端appid一致
     * 2、前端开发者必须加入开发者
     *
     * @param code
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long login(String code) {
        //1、获取code，用微信工具包获取一个openId
        String openid = null;

        try {
            WxMaJscode2SessionResult sessionInfo = service.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
            log.info("【小程序授权登陆】openId={}", openid);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

        //2、根据openId查询数据库
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerInfo::getWxOpenId, openid);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(queryWrapper);

        //3、如果第一次登陆，则注册，不是第一次登陆直接返回数据
        if (customerInfo == null) {
            customerInfo = new CustomerInfo();
            customerInfo.setWxOpenId(openid);
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfoMapper.insert(customerInfo);
        }

        //4、记录登陆日志
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("用户:" + customerInfo.getId() + "，小程序登陆");
        customerLoginLogMapper.insert(customerLoginLog);
        System.out.println("sjio1jdiiohja京哈后回收的i偶偶是:"+customerInfo.getId());
        //5、返回客户的id
        return customerInfo.getId();
    }

    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {
        //1、根据用户id查询用户
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
        //2.封装到vo对象
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo, customerLoginVo);
        //判断是否绑定了手机号码
        String phone = customerInfo.getPhone();
        boolean hasText = StringUtils.hasText(phone);
        customerLoginVo.setIsBindPhone(hasText);
        //3.返回vo对象
        return customerLoginVo;
    }

    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) throws WxErrorException {
        // 调用微信 API 获取用户的手机号
        WxMaPhoneNumberInfo phoneInfo = service.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
        String phoneNumber = phoneInfo.getPhoneNumber();
        log.info("phoneInfo:{}", JSON.toJSONString(phoneInfo));

        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setId(updateWxPhoneForm.getCustomerId());
        customerInfo.setPhone(phoneNumber);
        return this.updateById(customerInfo);

    }

    //获取客户的openid
    @Override
    public String getCustomerOpenId(Long customerId) {
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerInfo::getId, customerId);
        queryWrapper.select(CustomerInfo::getWxOpenId);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(queryWrapper);

        return customerInfo.getWxOpenId();
    }
}
